package com.quan.system.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.quan.common.bean.MailBean;
import com.quan.common.bean.PageBean;
import com.quan.common.bean.ResultBean;
import com.quan.common.core.MyBaseController;
import com.quan.common.utils.DateUtils;
import com.quan.common.utils.WebUtils;
import com.quan.system.common.amqp.producer.ProducerMessageSendMail;
import com.quan.system.common.dto.DimissionReasonRemarkDTO;
import com.quan.system.common.dto.employee.MailNotityDTO;
import com.quan.system.common.dto.employee.YearHolidayDTO;
import com.quan.system.common.dto.excel.EmpYearHolidayExportExcel;
import com.quan.system.common.dto.excel.SystemEmployeeImportExcel;
import com.quan.system.entity.SystemEmployee;
import com.quan.system.entity.SystemEmployeeDimissionRemark;
import com.quan.system.entity.SystemEmployeeJoinDimission;
import com.quan.system.service.SystemEmployeeDimissionRemarkService;
import com.quan.system.service.SystemEmployeeJoinDimissionService;
import com.quan.system.service.SystemEmployeeService;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.bean.BeanUtil;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-06-24
 */
@RestController
@RequestMapping("/system/employee")
public class SystemEmployeeController extends MyBaseController {

	@Autowired
	private SystemEmployeeService service;

	@Autowired
	private SystemEmployeeJoinDimissionService joinDimissionService;

	@Autowired
	private SystemEmployeeDimissionRemarkService dimissionRemarkService;

	@Autowired
	private ProducerMessageSendMail producerMessageSendMail;

	/**
	 * 添加
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/add")
	public Object add(@Valid @RequestBody SystemEmployee entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}

		if (this.service.hasExist("num", entity.getNum(), SystemEmployee.class)) {
			return ResultBean.warning("该值已存在");
		}

		boolean save = this.service.save(entity);
		if (save) {
			return ResultBean.ok("提交成功");
		} else {
			return ResultBean.failure("提交失败");
		}
	}

	/**
	 * 根据ID删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/deleteById/{id}")
	public Object deleteById(@PathVariable String id) {
		if (StringUtils.isNotBlank(id)) {
			boolean remove = this.service.removeById(id);
			if (remove) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + id + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 根据ID批量删除
	 * 
	 * @param idList ["1","2"]
	 * @return
	 */
	@PostMapping("/deleteBatchIds")
	public Object deleteBatchIds(@RequestBody List<String> idList) {
		if (null != idList && !idList.isEmpty()) {
			boolean remove = this.service.removeByIds(idList);
			if (remove) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + idList + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 修改
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/update")
	public Object update(@Valid @RequestBody SystemEmployee entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.failure(bindingResult.getFieldError().getDefaultMessage().toString());
		}
		boolean update = this.service.updateById(entity);
		if (update) {
			return ResultBean.ok("修改成功");
		} else {
			return ResultBean.failure("修改失败");
		}
	}

	/**
	 * 根据ID查询
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/get/{id}")
	public Object get(@PathVariable Long id) {
		SystemEmployee entity = this.service.getById(id);
		if (null != entity) {
			return ResultBean.ok(entity);
		} else {
			return ResultBean.failure("通过ID查询失败：[ " + id + " ]");
		}
	}

	/**
	 * 查询所有数据，不分页
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/list")
	public Object list(SystemEmployee entity) {
		return ResultBean.ok(this.service.list(new QueryWrapper<SystemEmployee>(entity).orderByDesc("ctime")));
	}

	/**
	 * 分页查询数据
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/page")
	public Object page(SystemEmployee entity) {
		return ResultBean.ok(this.service.selectEmployeePage(entity, new PageBean(request)));
	}

	/**
	 * 恢复已删除的员工
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/recoveryEmp/{id}")
	public Object recoveryEmp(@PathVariable Long id) {

		QueryWrapper<SystemEmployee> queryWrapper = new QueryWrapper<SystemEmployee>();
		queryWrapper.eq("id", id);
		queryWrapper.eq("deleted", 0);
		int count = this.service.count(queryWrapper);

		if (count == 0) {
			UpdateWrapper<SystemEmployee> updateWrapper = new UpdateWrapper<SystemEmployee>();
			updateWrapper.set("deleted", 0);
			updateWrapper.eq("id", id);
			updateWrapper.eq("deleted", 1);

			this.service.update(updateWrapper);
			return ResultBean.ok();
		} else {
			return ResultBean.failure("该员工已存在！");
		}

	}

	/**
	 * 员工离职原因勾选+自填
	 * 
	 * @param file
	 * @return
	 */
	@PostMapping("/dimissionReason")
	public Object dimissionReason(@RequestBody DimissionReasonRemarkDTO dto) {

		if (null != dto.getDimisionReasonId() && !dto.getDimisionReasonId().isEmpty()) {
			QueryWrapper<SystemEmployeeJoinDimission> queryWrapper = new QueryWrapper<SystemEmployeeJoinDimission>();
			queryWrapper.eq("emp_id", dto.getEmpId());
			this.joinDimissionService.remove(queryWrapper);

			dto.getDimisionReasonId().forEach(item -> {
				SystemEmployeeJoinDimission sejd = new SystemEmployeeJoinDimission();
				sejd.setEmpId(dto.getEmpId());
				sejd.setDimissionReasonId(item);
				this.joinDimissionService.save(sejd);
			});
		}

		if (null != dto.getRemarks() && !dto.getRemarks().isEmpty()) {
			QueryWrapper<SystemEmployeeDimissionRemark> queryWrapper = new QueryWrapper<SystemEmployeeDimissionRemark>();
			queryWrapper.eq("emp_id", dto.getEmpId());
			this.dimissionRemarkService.remove(queryWrapper);

			dto.getRemarks().forEach(item -> {
				SystemEmployeeDimissionRemark remark = new SystemEmployeeDimissionRemark();
				remark.setEmpId(dto.getEmpId());
				remark.setRemarks(item);
				this.dimissionRemarkService.save(remark);
			});
		}

		return ResultBean.ok();
	}

	/**
	 * 获取员工勾选的离职原因
	 * 
	 * @param empId
	 * @return
	 */
	@GetMapping(value = "/getJoinDimissionReasonByEmpId/{empId}")
	public Object getJoinDimissionReasonByEmpId(@PathVariable Long empId) {
		QueryWrapper<SystemEmployeeJoinDimission> queryWrapper = new QueryWrapper<SystemEmployeeJoinDimission>();
		queryWrapper.eq("emp_id", empId);
		return ResultBean.ok(this.joinDimissionService.list(queryWrapper));
	}

	/**
	 * 获取员工自填的离职原因
	 * 
	 * @param empId
	 * @return
	 */
	@GetMapping(value = "/getDimissionRemarksByEmpId/{empId}")
	public Object getDimissionRemarksByEmpId(@PathVariable Long empId) {
		QueryWrapper<SystemEmployeeDimissionRemark> queryWrapper = new QueryWrapper<SystemEmployeeDimissionRemark>();
		queryWrapper.eq("emp_id", empId);
		return ResultBean.ok(this.dimissionRemarkService.list(queryWrapper));
	}

	/**
	 * 导入员工数据
	 * 
	 * @param file
	 * @return
	 */
	@PostMapping("/importEmployeeData")
	public Object importEmployeeData(MultipartFile file, @RequestParam("isAccount") Boolean isAccount) {
		try {
			ImportParams params = new ImportParams(); // 默认跳过标题行
			List<SystemEmployeeImportExcel> emps = ExcelImportUtil.importExcel(file.getInputStream(), SystemEmployeeImportExcel.class, params);

			Integer importCount = this.service.importEmpInfoData(emps, isAccount);

			return ResultBean.ok("导出完成：总行数【" + emps.size() + "】，导入行数【" + importCount + "】");

		} catch (Exception e) {
			e.printStackTrace();
			return ResultBean.failure(e.getMessage());
		}
	}

	/**
	 * 根据籍贯统计员工数量
	 * 
	 * @return
	 */
	@GetMapping(value = "/reportEmpCountByArea")
	public Object reportEmpCountByArea() {
		return ResultBean.ok(this.service.reportEmpCountByArea());
	}

	/**
	 * 统计性别
	 * 
	 * @return
	 */
	@GetMapping(value = "/reportEmpCountByGender")
	public Object reportEmpCountByGender() {
		return ResultBean.ok(this.service.reportEmpCountByGender());
	}

	/**
	 * 统计户口性质
	 * 
	 * @return
	 */
	@GetMapping(value = "/reportEmpCountByHktype")
	public Object reportEmpCountByHktype() {
		return ResultBean.ok(this.service.reportEmpCountByHktype());
	}

	/**
	 * 统计在职状态
	 * 
	 * @return
	 */
	@GetMapping(value = "/reportEmpCountByWorkingStatus")
	public Object reportEmpCountByWorkingStatus() {
		return ResultBean.ok(this.service.reportEmpCountByWorkingStatus());
	}

	/**
	 * 统计日语级别
	 * 
	 * @return
	 */
	@GetMapping(value = "/reportEmpCountByJapLevel")
	public Object reportEmpCountByJapLevel() {
		return ResultBean.ok(this.service.reportEmpCountByJapLevel());
	}

	/**
	 * 统计婚姻状况
	 * 
	 * @return
	 */
	@GetMapping(value = "/reportEmpCountByMarital")
	public Object reportEmpCountByMarital() {
		return ResultBean.ok(this.service.reportEmpCountByMarital());
	}

	/**
	 * 统计学历
	 * 
	 * @return
	 */
	@GetMapping(value = "/reportEmpCountByEdu")
	public Object reportEmpCountByEdu() {
		return ResultBean.ok(this.service.reportEmpCountByEdu());
	}

	/**
	 * 统计毕业年份员工人数
	 * 
	 * @return
	 */
	@GetMapping(value = "/reportEmpCountByGraduDate")
	public Object reportEmpCountByGraduDate() {
		return ResultBean.ok(this.service.reportEmpCountByGraduDate());
	}

	/**
	 * 统计岗位人数
	 * 
	 * @return
	 */
	@GetMapping(value = "/reportEmpCountByPost")
	public Object reportEmpCountByPost() {
		return ResultBean.ok(this.service.reportEmpCountByPost());
	}

	/**
	 * 查询劳动合同即将到期的员工
	 * 
	 * @return
	 */
	@GetMapping(value = "/selectHTJJDQ")
	public Object selectHTJJDQ() {
		return ResultBean.ok(this.service.selectHTJJDQ());
	}

	/**
	 * 查询当月是否有年假员工
	 * 
	 * @return
	 */
	@GetMapping(value = "/selectNJJJDQ")
	public Object selectNJJJDQ() {
		return ResultBean.ok(this.service.selectNJJJDQ());
	}

	/**
	 * 年假邮件通知，合同到期邮件通知
	 * 
	 * @return
	 */
	@PostMapping(value = "/sendMailNotify")
	public Object sendMailNotify(@RequestBody MailNotityDTO dto) {
		if (null != dto && !dto.getToEmails().isEmpty()) {
			System.out.println(dto);
			System.out.println(StringUtils.join(dto.getToEmails(), ","));

			// 发送短信或邮件告知用户账号和密码
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("content", dto.getContent());

			MailBean mailBean = new MailBean();
			// mailBean.setTo(StringUtils.join(dto.getToEmails(), ","));
			mailBean.setTo("liping@whizen.com");
			mailBean.setSubject(dto.getSubject());
			mailBean.setTemplateLocation("/mail/Emp_Send_Notify.html");
			mailBean.setTemplateData(map);

			this.producerMessageSendMail.sender(mailBean);

			return ResultBean.ok();
		} else {
			return ResultBean.failure("收件人不能为空");
		}
	}

	/**
	 * 年假发放记录
	 * 
	 * @param dto
	 * @return
	 */
	@GetMapping("/yearHolidayList")
	public Object yearHolidayList(YearHolidayDTO dto) {
		if (null == dto.getMonths() || dto.getMonths().length == 0) {
			// 默认显示当前年所以员工的年假
			dto.setMonths(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
		}
		return ResultBean.ok(this.service.yearHolidayList(dto));
	}

	/**
	 * 导出员工年假到Excel
	 * 
	 * @param dto
	 * @return
	 */
	@GetMapping("/exportHolidayToExcel")
	public void exportHolidayToExcel(YearHolidayDTO dto) {
		if (null == dto.getMonths() || dto.getMonths().length == 0) {
			// 默认显示当前年所以员工的年假
			dto.setMonths(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
		}
		List<YearHolidayDTO> yearHolidayList = this.service.yearHolidayList(dto);

		try {
			//组装数据
			List<EmpYearHolidayExportExcel> objList = new ArrayList<EmpYearHolidayExportExcel>();
			
			int i=1;
			for (YearHolidayDTO holiday : yearHolidayList) {
				EmpYearHolidayExportExcel holidayExcel = new EmpYearHolidayExportExcel();
				holidayExcel.setOrder(i++);
				BeanUtil.copyProperties(holiday, holidayExcel);
				objList.add(holidayExcel);
			}
			
			//设置模板
			TemplateExportParams params = new TemplateExportParams("export/年假发放单模板.xlsx", true);
			
			//模板数据
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("year", DateUtils.getYear());
			map.put("month", StringUtils.join(dto.getMonths(), ","));
			map.put("list", objList);
			
			//导出
			Workbook workbook = ExcelExportUtil.exportExcel(params, map);
			
			//客户端下载
			String filename = "年假发放单"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) ;
			WebUtils.export(response, workbook, filename);
			
			logger.info("==>导出员工年假：{}", filename);
			
		} catch (Exception e) {
		}
	}
	
	

}
